package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 针对博客表进行封装的基本操作
 */
public class BlogDao {
    // 1. 插入博客
    public void insert (Blog blog) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            // 和数据库建立连接
            connection = DBUtil.getConnection();
            // 编写具体sql代码并封装
            String sql = "insert into blog values(null, ?, ?, now(), ?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, blog.getTitle());
            statement.setString(2, blog.getContent());
            statement.setInt(3, blog.getUserId());
            // 执行sql语句
            statement.executeUpdate();

            // 插入博客之后根据博客的userId更新数据库中用户的blogCount
            UserDao userDao = new UserDao();
            userDao.updateBlogCount(blog.getUserId(), 1);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            // 关闭连接，释放资源
            DBUtil.close(connection, statement, null);
        }
    }
    // 2. 获取博客表中对应用户的所有博客信息（博客列表页）
    public List<Blog> selectAll(int userId) {
        List<Blog> blogs = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 和数据库建立连接
            connection = DBUtil.getConnection();
            // 编写具体sql代码并封装，为了让最近的博客显示在最上面，需要加order by
            String sql = "select * from blog where userId = ? order by postTime desc";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            // 执行sql语句
            resultSet = statement.executeQuery();
            while(resultSet.next()) {
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));
                // 对博客内容太长的进行截断
                String content = resultSet.getString("content");
                if(content.length() > 200) {
                    content = content.substring(0, 100) + "...";
                }
                blog.setContent(content);
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                blog.setUserId(resultSet.getInt("userId"));
                blogs.add(blog);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            // 关闭连接，释放资源
            DBUtil.close(connection, statement, resultSet);
        }
        return blogs;
    }
    //    获取博客表中的所有博客信息（博客列表页）
    public List<Blog> selectAll() {
        List<Blog> blogs = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 和数据库建立连接
            connection = DBUtil.getConnection();
            // 编写具体sql代码并封装，为了让最近的博客显示在最上面，需要加order by
            String sql = "select * from blog order by postTime desc";
            statement = connection.prepareStatement(sql);
            // 执行sql语句
            resultSet = statement.executeQuery();
            while(resultSet.next()) {
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));
                // 对博客内容太长的进行截断
                String content = resultSet.getString("content");
                if(content.length() > 200) {
                    content = content.substring(0, 100) + "...";
                }
                blog.setContent(content);
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                blog.setUserId(resultSet.getInt("userId"));
                blogs.add(blog);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            // 关闭连接，释放资源
            DBUtil.close(connection, statement, resultSet);
        }
        return blogs;
    }
    // 3. 根据博客id获取博客的具体内容（博客详情页）
    public Blog selectBlog(int blogId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 和数据库建立连接
            connection = DBUtil.getConnection();
            // 编写具体sql代码并封装
            String sql = "select * from blog where blogId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, blogId);
            // 执行sql语句
            resultSet = statement.executeQuery();
            if(resultSet.next()) {
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));
                blog.setContent(resultSet.getString("content"));
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                blog.setUserId(resultSet.getInt("userId"));
                return blog;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            // 关闭连接，释放资源
            DBUtil.close(connection, statement, resultSet);
        }
        return null;
    }
    // 4. 根据博客id删除某一篇博客
    public void deleteBlog(int blogId) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            // 根据博客id获取到该博客的对象，继而获取到userId，方便之后对用户博客数量进行更新
            Blog blog = selectBlog(blogId);
            connection = DBUtil.getConnection();
            String sql = "delete from blog where blogId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, blogId);
            statement.executeUpdate();

            // 删除博客之后根据博客的userId更新数据库中用户的blogCount
            UserDao userDao = new UserDao();
            userDao.updateBlogCount(blog.getUserId(), -1);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }
    // 5. 修改博客的操作：先根据博客id删除旧的博客，再插入修改后的博客内容
    public void updateBlog(Blog blog) {
        deleteBlog(blog.getBlogId());
        insert(blog);
    }
}
